<template>
  <base-modal
    class="task-card-edit-dialog"
    :title="title"
    :show.sync="visible"
    width="700px"
    @closed="reset"
  >
    <div class="base-modal-content" v-if="init">
      <form-builder
        ref="form"
        :fields="fields"
        :value="form"
        :card-type="cardType"
        @update="update"
        :mode="mode"
      >
        <!-- start 备件 --> 
        <template slot="part" slot-scope="{ field, value }">
          <!-- start 客户字段 -->
          <form-item :label="field.displayName">
            <div class="input-and-btn">
              <biz-remote-select
                :value="value"
                :field="customerField"
                :remote-method="searchCustomer"
                @input="updateCustomer"
                :placeholder="$t('customer.detail.taskCard.cartEditDialog.form.part.placeholder')"
                :computed-width-keys="['name']"
              >
                <div
                  class="customer-template-option"
                  slot="option"
                  slot-scope="{ option }"
                >
                  <!-- <h3>{{ option.name }}</h3> -->
                 
                    <p>
                      <label>{{$t('customer.detail.taskCard.cartEditDialog.form.part.name')}}：</label>
                      <span>{{ option.name }}</span>
                    </p>
                    <p>
                      <label>{{$t('customer.detail.taskCard.cartEditDialog.form.part.serialNumber')}}：</label>
                      <span>{{ option.serialNumber }}</span>
                    </p>
                    <p>
                      <label>{{$t('customer.detail.taskCard.cartEditDialog.form.part.type')}}：</label>
                      <span>{{ option.type }}</span>
                    </p>
                    <p>
                      <label>{{$t('customer.detail.taskCard.cartEditDialog.form.part.standard')}}：</label>
                      <span>{{ option.standard }}</span>
                    </p>
                    
                </div>
              </biz-remote-select>
            </div>
          </form-item>
        </template>
        <!-- end 备件 -->
        <!-- start 用时时间 -->
        <template
          slot="usedTime"
          slot-scope="{ field, value }"
          v-if="isHoursRecord"
        >
          <form-item :label="field.displayName">
            <input
              class="usedTime"
              type="number"
              :value="value"
              :placeholder="field.placeHolder"
              disabled
            />
          </form-item>
        </template>
        <!-- end 用时时间 -->

        <!-- start 行程距离 -->
        <template slot="distance" slot-scope="{ field }" v-if="isHoursRecord">
          <form-item :label="field.displayName">
            <input
              class="distance"
              type="number"
              v-model="form.distance"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            />
          </form-item>
        </template>
        <!-- end 行程距离 -->
      </form-builder>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* util */
import * as Utils from '@src/component/form/util';
import { getPageLinkPart } from '@src/api/ProductV2Api';
import { safeNewDate } from '@src/util/time';
import i18n from '@src/locales'

export default {
  name: 'task-card-edit-dialog',
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Object,
      default: () => ({
        attribute: {},
      }),
    },
    isHoursRecord: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
      default: '',
    },
    cardType: {
      type: String,
      default: '',
    },
    cardName: {
      type: String,
      default: '',
    },
    product: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      visible: false,
      init: false,
      form: {
        part: [],
      },
      customerField: {
        isSystem: 1,
        fieldName: 'customer',
        displayName: i18n.t('customer.detail.taskCard.cartEditDialog.form.part.displayName'),
        formType: 'customer',
        defaultValue: null,
        isNull: 0,
        isSearch: 0,
        placeHolder: null,
      },
    };
  },
  computed: {
    /**
     * @description 弹窗标题
     */
    title() {
      // TODO 国际化 bell 传入的拼接翻译咋搞
      return this.action == 'edit'
        ? i18n.t('common.base.editModule', {module:this.cardName})
        : i18n.t('common.base.addModule', {module:this.cardName});
    },
    mode() {
      return `${this.cardType}_card`;
    },
  },
  methods: {
   async searchCustomer(params) {
       try {
         params = {
           id: this.product.catalogId,
           ...params
         }
        let result = await getPageLinkPart(params);
        result = result.result
        if (!result || !result.list) return;
        result.list = result.list.map((data) =>
          this.selectConversion(data)
        );
        return result;
      } catch (error) {
        console.warn(`${this.$options.name}: searchData -> error`, error);
      }
    },
    selectConversion(obj) {
      if(!obj) return {};
    
      let { name, id } = obj;
  
      return Object.freeze({
        label: name,
        value: id,
        ...obj
      })
    },
    updateCustomer(e) {
      this.form.part = e;
      if(!e.length) return;
      let item = e[0];
      this.fields.forEach((i)=>{
        if(i.formType == 'relationReplacementPart'){
          let {setting, fieldName} = i;
          this.$set(this.form, fieldName, item[setting.fieldName])
        }
      })
    },
    /**
     * @description 更新表单数据
     */
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;

      if (this.$appConfig.debug) {
        console.info(
          `[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(
            newValue
          )}`
        );
      }

      this.$set(this.form, fieldName, newValue);

      // 计算工时记录用时时间
      if (this.isHoursRecord) {
        if (fieldName == 'startTime' || fieldName == 'endTime')
          this.setUsedTime();
      }
    },
    /**
     * @description 弹窗关闭重置数据
     */
    reset() {
      this.form = {};
      this.init = false;
    },
    /**
     * @description 打开弹窗
     */
    openDialog() {
      this.visible = true;

      this.$nextTick(() => {
        this.unpack();
        this.init = true;
      });
    },
    /**
     * @description 将数据拆解成自定义表单可接收的数据
     */
    unpack() {
      let { attribute = {} } = this.value;
      let result = Utils.initialize(this.fields, { attribute });
      this.form = result;
      if (this.form.infoId) this.form.id = this.form.infoId;
      if (this.form.part) this.form.part = [this.form.part];//备件：新增返回空字符串，编辑返回是对象，组件接收数组。
    },
    /**
     * @description 表单验证
     */
    submit() {
      this.$refs.form
        .validate(false)
        .then(async valid => {
          if (!valid) return Promise.reject('validate fail.');

          // 判断工时记录的开始时间和结束时间
          if (this.isHoursRecord) {
            let { startTime, endTime } = this.form;
            if (startTime && endTime && startTime > endTime)
              return this.$platform.alert(this.$t('customer.detail.taskCard.cartEditDialog.submit.timeAlert'));
          }

          this.$emit('submit', this.form);
        })
        .catch(err => {
          console.error(err);
        });
    },
    /**
     * @description 计算用时时间
     * 结束时间-开始时间
     */
    setUsedTime() {
      let { startTime, endTime } = this.form;
      if (startTime && endTime) {
        let st = safeNewDate(startTime).getTime();
        let et = safeNewDate(endTime).getTime();
        let diff = (Math.abs(et - st) / 1000 / 60 / 60).toFixed(2);

        this.$set(this.form, 'usedTime', diff);
      }
    },
  },
};
</script>

<style lang="scss">
.task-card-edit-dialog {
  .usedTime,
  .distance {
    width: 100%;
  }
}
.customer-template-option{
  padding: 10px 0;
}
.customer-template-option p{
  line-height: 30px;
    margin: 0
}
</style>
